<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/
namespace app\common\library;
use think\Env;

/**
 * 获取微信用户信息
 */
class Wechat{

    const TEMPLATE_ID_CANCEL = 'p5GYKf2vW8fox5RgOfraA5nHzSuMOSxOgAAJf3caNxo';
    const TEMPLATE_ID_PAYED = 'lP6JQEoQLre3lr8lUypuGejyBEQ4ba6uHOKRBIwqd_Q';
    const TEMPLATE_ID_END = 'MoMdYPmu_zo_0_2Jk-35FTeN85QdQFruZWfs6nMka0s';
    //助教接单通知用户模板
    const TEMPLATE_ID_USER_ASSISTANT_RECEIVED = 'c1iZz_KpxQKDtFSZCIxzvZZE_gK2qYfSOdmooj4Vrgw';
    //用户取消助教订单通知助教模板
    const TEMPLATE_ID_USER_ASSISTANT_REFUND = 'bu1jn0XrpJajO9pcN8Qgx_GL5KJPl6cnI8LQv9I7_58';
    //助教取消订单通知用户模板
    const TEMPLATE_ID_ASSISTANT_USER__REFUND = 'Ofz1yqrtfqQRVXHKFh7uVQ2WDqvWpmATJ1JDEjOWw1k';
    //用户下单通知助教模板
    const TEMPLATE_ID_ASSISTANT_USER_ORDER = 'SaSatlliJtTuqmtZb5q3drhPOvxCupF4VRDKTlzwoO4';


    static $appid = 'wx123e314e24afa592';
    static $appSecret = '7c970944cfe7adc5a2b5b11da818bb8d';

    /**
     * 1、获取微信用户信息，判断有没有code，有使用code换取access_token，没有去获取code。
     * @return array 微信用户信息数组
     */
    public static function getUser($code){
        if (!isset($code)){//没有code，去微信接口获取code码
            return null;
        } else {//获取code后跳转回来到这里了
            $data = self::getAccessToken($code);//获取网页授权access_token和用户openid
            return $data;
            /*$data_all = self::getUserInfo($data['access_token'],$data['openid'],$_GET["url"]);//获取微信用户信息
            return $data_all;*/
        }
    }
    /**
     * 2、用户授权并获取code
     * @param string $callback 微信服务器回调链接url
     */
    /*private function get_code($callback){
        $appid = $this->appid;
        $scope = 'snsapi_userinfo';
        $state = md5(uniqid(rand(), TRUE));//唯一ID标识符绝对不会重复
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri='.urlencode($callback).'&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
        header("Location:$url");
    }*/
    /**
     * @param $code
     * @return mixed|void
     */
    public static function getAccessToken($code){
        $appid = self::$appid;
        $appSecret = self::$appSecret;
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $appSecret . '&js_code=' . $code . '&grant_type=authorization_code';
        $user = json_decode(file_get_contents($url));
        return json_decode(json_encode($user),true);//返回的json数组转换成array数组

    }

    static public function getServerAccessToken(){
        $redis = new \Redis();
        $redis->connect(config('redis.host'),config('redis.port'));
        if (!empty(config('redis.password'))){
            $redis->auth(config('redis.password'));
        }
        if ($user = $redis->get('wechat_access_token')){
            return json_decode($user,true);
        }else{
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.self::$appid.'&secret='.self::$appSecret;
            $user = json_decode(file_get_contents($url));
            $redis->setex('wechat_access_token',3600,json_encode($user));
            return json_decode(json_encode($user),true);//返回的json数组转换成array数组
        }

    }

    public static function getPhoneNumber($code)
    {
        $data['code'] = $code;
        $serverAccessToken = self::getServerAccessToken();
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$serverAccessToken['access_token'];
        $info = self::http_request($url,json_encode($data),'json');
        return json_decode($info,true);


    }

    /**
     * 使用access_token获取用户信息
     * @param $access_token
     * @param $openid
     * @param $pth
     * @return false|string|void
     */
    static function getUserInfo($accessToken,$openid,$pth){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $accessToken . '&openid=' . $openid . '&lang=zh_CN';
        $user = file_get_contents($url);
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;
            exit;
        }
        $s=$pth==''?"?":"&";
        // var_dump( $_SERVER);
        echo $_SERVER["REQUEST_SCHEME"]."://".$_SERVER['HTTP_HOST']."/".$pth.$s."val=".$user;
        header("Location:". $_SERVER["REQUEST_SCHEME"]."://".$_SERVER['HTTP_HOST']."/quest/Assessment/index.php 这里配置返回地址".$pth.$s."val=".urlencode($user));
        return $user;
    }

    static function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json'
            ));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);

        return $output;
        exit();

    }

    public function getUnlimited($scene,$page,$env_version='release'){
        $selfAccessToken = self::getServerAccessToken();
        //$data['access_token'] =$selfAccessToken['access_token'];
        $data['scene'] = $scene;
        $data['page'] = $page;
        $data['check_path'] = true;
        //正式版为 "release"，体验版为 "trial"，开发版为 "develop"
        $data['env_version'] = $env_version ? : config('wechat.scancode_env');
        $data['width'] = '500';
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$selfAccessToken['access_token'];
        return self::http_request($url,json_encode($data));
    }

    public function publishMsg($toOpenId,$params,$templateId,$page='page_main/views/teamDetails',$miniprogram_state = 'formal')
    {
        $selfAccessToken = self::getServerAccessToken();
        $data['touser'] = $toOpenId;
        $data['template_id'] = $templateId;
        $data['miniprogram_state'] =$miniprogram_state;
        $data['page'] = $page;

        if ($templateId == self::TEMPLATE_ID_CANCEL){
            $data['data'] = [
                'thing1' => [
                    'value' => $params['title'] ?? ''
                ],
                'date2' => [
                    'value' => $params['date'] ?? date('Y-m-d H:i', time())
                ],
                'thing3' => [
                    'value' => $params['address']
                ],
                'thing5' => [
                    'value' => $params['reason']
                ],
                'amount6' => [
                    'value' => $params['amount']
                ],
            ];
        }else if ($templateId == self::TEMPLATE_ID_PAYED){
            $data['data'] = [
                'thing4' => [
                    'value' => $params['title'] ?? ''
                ],
                'date3' => [
                    'value' => $params['date'] ?? date('Y-m-d H:i', time())
                ],
                'thing6' => [
                    'value' => $params['address']
                ],
                'number9' => [
                    'value' => $params['numbers']
                ],
                'thing7' => [
                    'value' => $params['notice']
                ],
            ];
        }else if($templateId == self::TEMPLATE_ID_END){
            $data['data'] = [
                'thing1' => [
                    'value' => $params['title'] ?? ''
                ],
                'time4' => [
                    'value' => $params['start_date'] ?? date('Y-m-d H:i', time())
                ],
                'time5' => [
                    'value' => $params['end_date'] ?? date('Y-m-d H:i', time())
                ],
                'thing3' => [
                    'value' => $params['notice']
                ]
            ];
        }else if($templateId == self::TEMPLATE_ID_USER_ASSISTANT_REFUND){
            $data['data'] = [
                'thing8' => [
                    'value' => $params['title'] ?? ''
                ],
                'time6' => [
                    'value' => $params['date'] ?? date('Y-m-d H:i:s', time())
                ],
                'character_string11' => [
                    'value' => $params['order'] ?? ''
                ],
                'thing10' => [
                    'value' => $params['noticer']
                ]
            ];
        }else if($templateId == self::TEMPLATE_ID_ASSISTANT_USER__REFUND){
            $data['data'] = [
                'character_string8' => [
                    'value' => $params['order'] ?? ''
                ],
                'thing7' => [
                    'value' => $params['reason']
                ],
                'thing4' => [
                    'value' => $params['notice']
                ]
            ];
        }

        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$selfAccessToken['access_token'];
        return self::http_request($url,json_encode($data));
    }

    public static function publishMsgDevice($toOpenId,$templateId,$page='pagesE/index/detail',$miniprogram_state = 'formal')
    {
        $templateInfo = UserWechatSubscribe::where('template_id',$templateId)->where('statusswitch',UserWechatSubscribe::STATUS_SWITCH_ENABLE)->find();
        if (!$templateInfo){
            return false;
        }
        $selfAccessToken = self::getServerAccessToken();
        $data['to_openid_list'] = [$toOpenId];
        $data['template_id'] = $templateId;
        $data['sn'] = $templateInfo->sn;
        $data['miniprogram_state'] = $miniprogram_state;
        $data['model_id'] = $templateInfo->model_id;
        //$data['page'] = '';
        $data['data'] = [
            'time1'=>[
                'value'=> date('Y-m-d H:i:s')
            ],
            'enum_string2'=>[
                'value'=>'智能垃圾箱'
            ],

            'character_string3'=>[
                'value'=>'LJFL00001860602067467359'
            ],
            'enum_string4'=>[
                'value'=>'满溢报警'
            ],
            'enum_string5'=>[
                'value'=>'箱体发生满溢报警，请尽快处理'
            ]
        ];

        $url = 'https://api.weixin.qq.com/cgi-bin/message/device/subscribe/send?access_token='.$selfAccessToken['access_token'];
        return self::http_request($url,json_encode($data));
    }

    public static function getTemplateList()
    {
        $selfAccessToken = self::getServerAccessToken();
        $url = 'https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token='.$selfAccessToken['access_token'];
        return self::http_request($url,[]);
    }

    public static function snTicket($sn,$model_id)
    {
        $selfAccessToken = self::getServerAccessToken();
        $data['sn'] = $sn;
        $data['model_id'] = $model_id;

        $url = 'https://api.weixin.qq.com/wxa/getsnticket?access_token='.$selfAccessToken['access_token'];
        return self::http_request($url,json_encode($data));
    }
}